package com.aishua.fire.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.aishua.fire.common.Base64Util;
import com.aishua.fire.common.FileUtil;
import com.aishua.fire.common.ImgFileUtil;
import com.aishua.fire.common.JsonObjectResult;
import com.aishua.fire.common.UpLoadUtil;
import com.aishua.fire.entity.app.MongoImageRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value = "图片上传接口", tags = { "图片上传接口" })
@Controller
@Slf4j
public class PicUploadController {

	@Autowired
	private ImgFileUtil imgFileUtil;
	
	@Value("${project.imgupload.rootPath}")
	private String uploadPath;;
	
	 @Value("${project.imgreq.rootPath}")
	  private String rootPath;
	 
	 @Value("${server.path}")
		private String path;

	@SuppressWarnings("rawtypes")
	@ApiOperation(value="图片上传接口")
	@PostMapping(value = {"/pic"} )
	public ResponseEntity<JsonObjectResult> fileupload(@RequestParam("file") MultipartFile file) {
		String contentType = file.getContentType();
		log.info("contentType为:{}",contentType);
		try {
			String reqPath = imgFileUtil.writeFileInServer(file);
			log.info("请求文件路径为:{}",reqPath);
			JsonObjectResult r = JsonObjectResult.makeSuccessResult(reqPath);
			return ResponseEntity.ok(r);
		} catch (IOException e) {
			log.error("上传文件失败:{}",e);
		}
		JsonObjectResult r = JsonObjectResult.makeErrorResult(null);
		return ResponseEntity.ok(r);
    }
	
	@SuppressWarnings("rawtypes")
	@ApiOperation(value="文件上传接口")
	@PostMapping(value = {"/upload"} )
	public ResponseEntity<JsonObjectResult> filesupload(@RequestParam("file") MultipartFile file) {
		//防止文件名重复，得到一个uid作为文档名
		String newFileName = UUID.randomUUID().toString().replace("-", "");;
		String fileName = file.getOriginalFilename();
		//获取文件类型
		String suffix = fileName.substring(fileName.indexOf("."), fileName.length());
		String destination = uploadPath+"file/"+newFileName+suffix;
		FileUtil.uploadImage(file, destination);
		Map<String, String> fileNameMap = new HashMap<>();
//		String newName ="http://"+ path+":"+"8080" + rootPath +"file/"+ newFileName+suffix;
		fileNameMap.put(fileName, newFileName+suffix);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(fileNameMap.toString());
		return ResponseEntity.ok(r);
	    }

	
	@SuppressWarnings("rawtypes")
	@ApiOperation(value="文件下载获取文件大小接口")
	@GetMapping(value = {"/upload"} )
	public ResponseEntity<JsonObjectResult> downloadFile(@RequestParam("fileUrl") String fileUrl) {
		File file=new File(fileUrl);
		if(!file.isFile()){
			return null;
		}
		// 获取文件大小
		int buff;
		FileInputStream  input = null;
		try {
			input = new FileInputStream(file);
			buff = input.available();
			input.close();
			log.info("文件大小为：{}",buff);
		} catch (Exception e) {
			throw new RuntimeException("文件下载失败");
		}
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(file.length());
		return ResponseEntity.ok(r);
	}
	
	
	@PostMapping(value = "/uploadPictures")
    @ApiOperation(value = "通过批量图片base64上传图片返回图片id", notes = "通过批量图片base64上传图片返回图片id")
    public ResponseEntity<JsonObjectResult> uploadPictures(@RequestBody MongoImageRequest mongoImageRequest) {

        List<Object> urls = new ArrayList<Object>();
        JsonObjectResult r;
        List<String> picBase64s = mongoImageRequest.getPictureDatas();
        //空处理
        if (picBase64s.size() < 1) {
             r=JsonObjectResult.makeErrorResult("图片不存在");
             return ResponseEntity.ok(r);
        }
        for (String picBase64 : picBase64s) {
            mongoImageRequest.setPictureData(picBase64);
            r = uploadPicture(mongoImageRequest);
            urls.add(r.getData());
        }


         r = JsonObjectResult.makeSuccessResult(urls);
		return ResponseEntity.ok(r);
    }
	
	   /**
     * 3.5.1 通过单个图片base64、创建人、应用来源、业务类型、后缀名上传图片返回图片id
     */
    @PostMapping(value = "/uploadPicture", consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation(value = "通过单个图片base64、后缀名上传图片返回图片id", notes = "通过单个图片base64、创建人、应用来源、业务类型、后缀名上传图片返回图片id")
    public JsonObjectResult uploadPicture(@RequestBody MongoImageRequest mongoImageRequest) {

    	 JsonObjectResult r;
        String picBase64 = mongoImageRequest.getPictureData();
        //空处理
        if (StringUtils.isBlank(picBase64)) {
        	 r=JsonObjectResult.makeErrorResult("图片不存在");
        }

        //将base64还原成字节
        byte[] bytes = Base64Util.decode(picBase64);

        //文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");

//        String createBy = StringUtils.isNotBlank(mongoImageRequest.getCreateBy()) ?  mongoImageRequest.getCreateBy(): "unknown";
//        String application = StringUtils.isNotBlank(mongoImageRequest.getApplication()) ? mongoImageRequest.getApplication(): "unknown"    ;
//        String business = StringUtils.isNotBlank(mongoImageRequest.getBusiness()) ? mongoImageRequest.getBusiness() : "unknown";
        String suffix = StringUtils.isNotBlank(mongoImageRequest.getSuffix()) ? mongoImageRequest.getSuffix() : "jpg";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());

        String str1 = date.substring(0, 6);
        String str2 = date.substring(4, 8);

        //根路径+上传路径+业务类型+年月+日
        String returnUrl = uploadPath +   "/" + str1 + "/" + str2 + "/" + fileName + "." + suffix;
        String filePath = rootPath + returnUrl;


        try {
            UpLoadUtil.uploadImg(bytes, filePath);
            r = JsonObjectResult.makeSuccessResult(null);

        } catch (Exception e) {
            log.info("pic upload Exception error:" + e.getMessage());
            r=JsonObjectResult.makeErrorResult("上传失败");
        }


        r = JsonObjectResult.makeSuccessResult(null);
		return r;
    }
	
}
